package util;

import java.sql.*;

public class DataBase {
    private static String url = "jdbc:mysql://localhost:3306/tblogdatabase?useSSL=false";//tblogdatabase是表的名字;
    private static String user = "root";
    private static String password = "123456";
    private static Connection conn = null;
    private static PreparedStatement preparedStatement = null;
    private static ResultSet resultSet = null;
    private static int id=0;

    //数据库的初始化
    public static void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动
            conn = DriverManager.getConnection(url, user, password);//连接数据库
        } catch (ClassNotFoundException e) {
            System.out.println("数据库连接异常，初始化失败");
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //数据库的增删改操作
    public static int operate(String sql) {
        int flag = 0;
        try {
            preparedStatement = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            flag = preparedStatement.executeUpdate();
            resultSet = preparedStatement.getGeneratedKeys();
        } catch (SQLException sqlException) {
            System.out.println("数据库增删改异常，操作失败");
            sqlException.printStackTrace();
        }
        return flag;
    }

    //数据库的查询操作
    public static ResultSet inquire(String sql) {
        try {
            preparedStatement = conn.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
        } catch (SQLException sqlException) {
            System.out.println("数据库查询异常，操作失败");
            sqlException.printStackTrace();
        }
        return resultSet;
    }

    //获取数据库自增id
    public static int getId() throws SQLException {
        while (resultSet.next()){
            id=resultSet.getInt(1);
        }
        return id;
    }
    //数据库的释放资源
    public static void release() {
        try {
            if (conn != null) {
                conn.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            System.out.println("数据库断连异常");
            e.printStackTrace();
        }
    }
}